package utils

import (
	"fmt"
	"gitee.com/chejiangyi/bsfgo/core/base2"
	"github.com/fsnotify/fsnotify"
	"github.com/spf13/viper"
	"time"
)

var ConfigUtil = &ConfigUtilTool{}
var lastConfigChangeTime = time.Now()

type ConfigUtilTool struct {
}

func (*ConfigUtilTool) GetConfig() *viper.Viper {
	return viper.GetViper()
}

func (*ConfigUtilTool) InitConfig(filename string) {
	if StringUtil.IsEmpty(filename) {
		filename = "config." + EnvUtil.GetEnv() + "." + EnvUtil.GetConfigType()
	}
	dirs := []string{"web/resources/", "resources/", ""}
	for _, dir := range dirs {
		filename2 := dir + filename
		if FileUtil.FileExist(filename2) {
			viper.SetConfigFile(filename2)
			viper.WatchConfig()
			viper.OnConfigChange(func(e fsnotify.Event) {
				if time.Since(lastConfigChangeTime).Seconds() > 1 { //限定一秒
					LogUtil.Info("检测到配置文件发生变更:%s", e.String())
					lastConfigChangeTime = time.Now()
				}
			})
			err := viper.ReadInConfig()
			if err != nil {
				errMsg := fmt.Sprintf("配置文件加载错误:%s", filename2)
				panic(base2.NewBsfError2(errMsg, err))
			}
			LogUtil.Info(fmt.Sprintf("配置文件加载成功:%v", filename2))
			return
		}
	}
	panic(base2.NewBsfError(fmt.Sprintf("配置文件不存在:%s", filename)))

}

func (*ConfigUtilTool) Get(key string, defaultValue any) any {
	if viper.IsSet(key) == false {
		return defaultValue
	}
	return viper.Get(key)
}

func (*ConfigUtilTool) Has(key string) bool {
	return viper.IsSet(key)
}
